<?php
/**
 * 阿里云百炼平台文件上传示例
 * 演示如何上传JSON文件并获取file-id
 */

// 配置API密钥（请替换为您的实际API密钥）
$apiKey = 'sk-416b931b781c420c9f6331b7346962b5';

// 文件路径
$filePath = __DIR__ . 'uploads/fa_food_ingredient.json';

// 检查文件是否存在
if (!file_exists($filePath)) {
    die("文件不存在: $filePath\n");
}

// 使用curl上传文件
$ch = curl_init();

// 设置请求URL
curl_setopt($ch, CURLOPT_URL, 'https://dashscope.aliyuncs.com/compatible-mode/v1/files');

// 设置请求头
$headers = [
    "Authorization: Bearer $apiKey",
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

// 设置POST数据
$postData = [
    'file' => new CURLFile($filePath),
    'purpose' => 'file-extract'
];
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

// 其他设置
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

// 执行请求
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);

// 处理响应
if ($error) {
    echo "请求错误: $error\n";
} else {
    echo "HTTP状态码: $httpCode\n";
    echo "响应内容: $response\n";
    
    // 解析JSON响应
    $result = json_decode($response, true);
    if (json_last_error() === JSON_ERROR_NONE) {
        if (isset($result['id'])) {
            echo "文件上传成功，file-id: " . $result['id'] . "\n";
            echo "文件名: " . $result['filename'] . "\n";
            echo "大小: " . $result['bytes'] . " 字节\n";
        } else {
            echo "上传失败: " . (isset($result['message']) ? $result['message'] : '未知错误') . "\n";
        }
    } else {
        echo "响应不是有效的JSON格式\n";
    }
}
?>